//
//  Network.swift
//  SHMath
//
//  Created by zhuxuhong on 2017/9/27.
//  Copyright © 2017年 北大方正电子. All rights reserved.
//

import Alamofire
import UIKit

extension Network{
	typealias RequestCompletion = ((_ error: String?, _ data: Data?) -> Void)
	
	typealias Success = ((_ json: Any) -> Void)
	typealias Failure = ((_ error: String) -> Void)
}

extension NetworkReachabilityManager{
	static let shared = NetworkReachabilityManager(host: "www.baidu.com")
}

extension Network{
	fileprivate static func showNotReachableTipper(){
		Tipper.snackBar(style: .warning, message: "你的网络似乎已断开连接哦", action: TipperSnackBar.Action.init(title: "去检查", handler: { 
			UIApplication.shared.openURL(url: UIApplicationOpenSettingsURLString)
		}))
	}
	
	public static func listenReachability(){
		let status = NetworkReachabilityManager.shared?.networkReachabilityStatus
		if status == .notReachable {
			showNotReachableTipper()
		}
		
		NetworkReachabilityManager.shared?.listenerQueue = .main
		NetworkReachabilityManager.shared?.listener = 
		{ status in
			switch status {
			case .unknown:
				Tipper.toast(message: "未知网络状态")
			case .notReachable: showNotReachableTipper()
			case .reachable(let type):
				TipperHUD.removeAll()
				
				if type == .wwan{
					Tipper.toast(message: "正在使用移动网络")
				}
				else{					
					Tipper.toast(message: "正在使用WiFi网络")
				}
			}
		}
		NetworkReachabilityManager.shared?.startListening()
	}
}

struct Network {
	fileprivate static func handleResponse(_ response: DataResponse<Data>, completion: @escaping Network.RequestCompletion){
		
		TipperHUD.removeAll()
		
		print("[Request Url]: \(response.request?.url?.absoluteString ?? "")")
		
		guard response.result.error == nil else{
			completion("网络请求失败", nil)
			return
		}
		guard let httpResponse = response.response, 
			httpResponse.statusCode == 200, 
			let data = response.data else{
				completion("网络请求失败", nil)
				return
		}
		completion(nil, data)
	}
	
	public static func request(url: String,
							   method: HTTPMethod,
							   encoding: API.Encoding,
	                           parameters: Parameters? = nil, 
	                           completion: @escaping Network.RequestCompletion)
	{
		Alamofire.request(url, method: method, parameters: parameters, encoding: encoding).responseData(queue: DispatchQueue.main) { response in
			handleResponse(response, completion: completion)
		}
	}
}
